import { useEffect, useMemo, useRef, useState } from "react";
import { Link, useLocation } from "react-router-dom";
import styles from "./index.module.scss";
import thumb1 from "../../../assets/thumb/thumb1.png";
import thumb2 from "../../../assets/thumb/thumb2.png";
import thumb3 from "../../../assets/thumb/thumb3.png";
import { useSelector } from "react-redux";

declare const window: any;

type VideoItem = {
  id: number;
  name: string;
  thumb: string;
  url: string;
};

const allGrades = ["托班上","托班下","小班上","小班下","中班上","中班下","大班上","大班下","视频欣赏"];

const sampleList: VideoItem[] = [
  { id: 1, name: "入园适应·体验活动一", thumb: thumb1, url: "https://media.w3.org/2010/05/sintel/trailer.mp4" },
  { id: 2, name: "游戏·探索区角", thumb: thumb2, url: "https://media.w3.org/2010/05/bunny/trailer.mp4" },
  { id: 3, name: "规律作息·午间安静", thumb: thumb3, url: "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4" },
  { id: 4, name: "亲子活动·合作绘画", thumb: thumb2, url: "https://media.w3.org/2010/05/sintel/trailer.mp4" },
  { id: 5, name: "户外·投掷练习", thumb: thumb3, url: "https://media.w3.org/2010/05/bunny/trailer.mp4" },
  { id: 6, name: "区域·建构游戏", thumb: thumb1, url: "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4" },
];

const useQuery = () => {
  const { search } = useLocation();
  return useMemo(() => new URLSearchParams(search), [search]);
};

const LibraryVideosPage = () => {
  const systemConfig = useSelector((state: any) => state.systemConfig.value);
  const query = useQuery();
  const group = query.get("group") || "悦读树";
  const initGrade = query.get("grade") || "小班上";
  const [grade, setGrade] = useState(initGrade);
  const [showPlayer, setShowPlayer] = useState(false);
  const [current, setCurrent] = useState<VideoItem | null>(null);
  const playerInitedRef = useRef(false);

  useEffect(() => {
    document.title = `${group} · ${grade}`;
  }, [group, grade]);

  useEffect(() => {
    if (showPlayer && current && !playerInitedRef.current) {
      initDPlayer(current.url);
      playerInitedRef.current = true;
    }
    return () => {
      if (!showPlayer && window.player) {
        try {
          window.player.destroy();
        } catch {}
        playerInitedRef.current = false;
      }
    };
  }, [showPlayer, current]);

  const initDPlayer = (playUrl: string) => {
    window.player = new window.DPlayer({
      container: document.getElementById("meedu-player-container"),
      autoplay: false,
      video: {
        url: playUrl,
        pic: systemConfig.playerPoster || "",
      },
    });
  };

  return (
    <div className={styles.page}>
      <div className={styles.header}>
        <Link to="/library" aria-label="关闭" className={styles.close}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
          </svg>
        </Link>
        <div className={styles.title}>{group} · {grade}</div>
        <div style={{ width: 28 }} />
      </div>

      <div className={styles.tabs}>
        {allGrades.map((g) => (
          <button
            key={g}
            className={`${styles.tab} ${grade === g ? styles.tabActive : ""}`}
            onClick={() => setGrade(g)}
          >
            {g.replace("上","（上）").replace("下","（下）")}
          </button>
        ))}
      </div>

      <div className={styles.grid}>
        {sampleList.map((v) => (
          <div key={v.id} className={styles.card} onClick={() => { setCurrent(v); setShowPlayer(true); }}>
            <div className={styles.thumbWrap}>
              <img className={styles.thumb} src={v.thumb} alt={v.name} />
              <span className={styles.playIcon} aria-hidden="true">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M8 5v14l11-7z" />
                </svg>
              </span>
            </div>
            <div className={styles.name}>{v.name}</div>
          </div>
        ))}
      </div>

      <div className={styles.loadMore}>~ 加载更多 ~</div>

      {showPlayer && current && (
        <div className={styles.mask} onClick={() => setShowPlayer(false)}>
          <div className={styles.playerPanel} onClick={(e) => e.stopPropagation()}>
            <div className={styles.playerHeader}>
              <div>{current.name}</div>
              <button className={styles.closeBtn} onClick={() => setShowPlayer(false)}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                  <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
                </svg>
              </button>
            </div>
            <div id="meedu-player-container" className={styles.playerBody}></div>
          </div>
        </div>
      )}
    </div>
  );
};

export default LibraryVideosPage;


